/**
*┌──────────────────────────────────────────────────────────────┐
*│　描    述：User_groups接口实现                                                    
*│　作    者：NetCoreCMS                                            
*│　版    本：1.0    模板代码自动生成                                                
*│　创建时间：2019-12-25 10:52:46                             
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│　命名空间： NetCoreCMS.Repository.SqlServer                                  
*│　类    名： User_groupsRepository                                      
*└──────────────────────────────────────────────────────────────┘
*/
using NetCoreCMS.DbHelper;
using NetCoreCMS.IRepository;
using NetCoreCMS.Models;
using Dapper;
using Microsoft.Extensions.Options;
using System;
using System.Threading.Tasks;
using System.Text;
using System.Linq;
using System.Transactions;
using System.Data;

namespace NetCoreCMS.Repository.SqlServer
{
    public class User_groupsRepository:BaseRepository<User_groups,Int32>, IUser_groupsRepository
    {
        public User_groupsRepository(IOptionsSnapshot<DbOption> options)
        {
            _dbOption =options.Get("NetCoreCMS");
            if (_dbOption == null)
            {
                throw new ArgumentNullException(nameof(DbOption));
            }
            //_dbConnection = ConnectionFactory.CreateConnection(_dbOption.DbType, _dbOption.ConnectionString);
        }

        public bool DeleteAll(int id)
        {
            using (TransactionScope scope = new TransactionScope())
            {
                using (IDbConnection _dbConnection = ConnectionFactory.CreateConnection(_dbOption.DbType, _dbOption.ConnectionString))
            {
                
                    var flag= _dbConnection.Execute("delete from [" + nameof(User_group_price) + "] where group_id=@group_id;delete from [User_groups] where id=@id", new { group_id = id, id = id }) > 0;
                    scope.Complete();
                    return flag;
                }
            }
        }

        public User_groups GetUpgrade(int group_id, int exp)
        {
            using (IDbConnection _dbConnection = ConnectionFactory.CreateConnection(_dbOption.DbType, _dbOption.ConnectionString))
            {
                StringBuilder strSql = new StringBuilder();
                strSql.Append("select top 1 * from [" + nameof(User_groups) + "]");
                strSql.Append(" where is_lock=0 and is_upgrade=1");
                strSql.Append(" and grade>(select grade from [" + nameof(User_groups) + "] where id=@group_id) and upgrade_exp<=@exp");
                strSql.Append(" order by grade asc");
                return _dbConnection.Query<User_groups>(strSql.ToString(), new { group_id = group_id, exp = exp }).FirstOrDefault();
            }
        }
    }
}